//! # 配置中心核心抽象层
//!
//! 提供配置中心的核心抽象接口定义，专注于配置管理的核心功能。
//!
//! ## 设计原则
//!
//! * **单一职责原则** - 专注于配置管理核心功能
//! * **面向接口编程** - 通过trait定义清晰的接口边界
//! * **依赖倒置原则** - 高层模块不依赖低层模块具体实现
//! * **开闭原则** - 对扩展开放，对修改封闭
//!
//! ## 核心接口
//!
//! * [`ConfigurationProvider`] - 配置提供者核心接口
//! * [`ConfigurationStorage`] - 配置存储抽象接口
//! * [`ConfigurationEncryption`] - 配置加密抽象接口
//! * [`ConfigurationAudit`] - 配置审计抽象接口
//! * [`ConfigurationCache`] - 配置缓存抽象接口
//! * [`ConfigurationNotifier`] - 配置通知抽象接口

use std::collections::HashMap;
use std::time::SystemTime;

use async_trait::async_trait;
use serde::{Deserialize, Serialize};

use crate::RustCloudConfig;

/// 配置环境信息
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct ConfigEnvironment {
    /// 应用名称
    pub application: String,
    /// 环境配置（dev/test/prod等）
    pub profile: String,
    /// 版本标签（通常为Git标签或分支）
    pub label: String,
}

impl ConfigEnvironment {
    /// 创建新的配置环境
    pub fn new(application: &str, profile: &str, label: &str) -> Self {
        Self {
            application: application.to_string(),
            profile: profile.to_string(),
            label: label.to_string(),
        }
    }

    /// 获取配置键
    pub fn key(&self) -> String {
        format!("{}:{}:{}", self.application, self.profile, self.label)
    }
}

impl Default for ConfigEnvironment {
    fn default() -> Self {
        Self::new("application", "default", "main")
    }
}

/// 配置响应数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigurationData {
    /// 环境信息
    pub environment: ConfigEnvironment,
    /// 配置内容
    pub config: RustCloudConfig,
    /// 版本号
    pub version: String,
    /// 最后修改时间
    pub last_modified: SystemTime,
    /// 配置源
    pub source: String,
    /// 扩展属性
    pub properties: HashMap<String, serde_json::Value>,
}

/// 配置变更记录
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigurationChange {
    /// 变更ID
    pub id: String,
    /// 环境信息
    pub environment: ConfigEnvironment,
    /// 操作类型
    pub operation: ChangeOperation,
    /// 操作用户
    pub user: String,
    /// 变更时间
    pub timestamp: SystemTime,
    /// 变更描述
    pub description: String,
    /// 变更前配置
    pub old_config: Option<RustCloudConfig>,
    /// 变更后配置
    pub new_config: Option<RustCloudConfig>,
    /// 变更详情
    pub details: HashMap<String, ChangeDetail>,
}

/// 变更操作类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ChangeOperation {
    /// 创建配置
    Create,
    /// 更新配置
    Update,
    /// 删除配置
    Delete,
    /// 回滚配置
    Rollback,
}

/// 变更详情
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChangeDetail {
    /// 字段路径
    pub path: String,
    /// 旧值
    pub old_value: Option<serde_json::Value>,
    /// 新值
    pub new_value: Option<serde_json::Value>,
}

/// 配置通知事件
#[derive(Debug, Clone)]
pub struct ConfigurationEvent {
    /// 事件类型
    pub event_type: EventType,
    /// 环境信息
    pub environment: ConfigEnvironment,
    /// 配置数据
    pub data: Option<ConfigurationData>,
    /// 事件时间
    pub timestamp: SystemTime,
    /// 额外信息
    pub metadata: HashMap<String, String>,
}

/// 事件类型
#[derive(Debug, Clone, PartialEq)]
pub enum EventType {
    /// 配置更新
    ConfigurationUpdated,
    /// 配置删除
    ConfigurationDeleted,
    /// 配置创建
    ConfigurationCreated,
    /// 服务器状态变更
    ServerStatusChanged,
    /// 缓存刷新
    CacheRefreshed,
}

/// 配置中心核心结果类型
pub type ConfigurationResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;

/// 配置提供者核心接口
/// 
/// 这是配置中心的最高层抽象，定义了配置获取的统一接口
#[async_trait]
pub trait ConfigurationProvider: Send + Sync {
    /// 获取配置
    async fn get_configuration(&self, environment: &ConfigEnvironment) -> ConfigurationResult<ConfigurationData>;
    
    /// 检查配置是否存在
    async fn exists(&self, environment: &ConfigEnvironment) -> ConfigurationResult<bool>;
    
    /// 列出所有应用
    async fn list_applications(&self) -> ConfigurationResult<Vec<String>>;
    
    /// 列出应用的所有配置文件
    async fn list_profiles(&self, application: &str) -> ConfigurationResult<Vec<String>>;
    
    /// 列出应用环境的所有标签
    async fn list_labels(&self, application: &str, profile: &str) -> ConfigurationResult<Vec<String>>;
}

/// 配置存储抽象接口
/// 
/// 定义配置持久化存储的统一接口，支持多种存储后端
#[async_trait]
pub trait ConfigurationStorage: Send + Sync {
    /// 加载配置
    async fn load(&self, environment: &ConfigEnvironment) -> ConfigurationResult<ConfigurationData>;
    
    /// 保存配置
    async fn save(&self, data: &ConfigurationData, user: &str) -> ConfigurationResult<String>;
    
    /// 删除配置
    async fn delete(&self, environment: &ConfigEnvironment, user: &str) -> ConfigurationResult<()>;
    
    /// 获取配置历史
    async fn get_history(&self, environment: &ConfigEnvironment) -> ConfigurationResult<Vec<ConfigurationChange>>;
    
    /// 回滚到指定版本
    async fn rollback(&self, environment: &ConfigEnvironment, version: &str, user: &str) -> ConfigurationResult<()>;
    
    /// 初始化存储
    async fn initialize(&self) -> ConfigurationResult<()>;
}

/// 配置加密抽象接口
/// 
/// 提供配置加密解密的统一接口，支持多种加密算法
#[async_trait]
pub trait ConfigurationEncryption: Send + Sync {
    /// 加密配置
    async fn encrypt(&self, config: &mut RustCloudConfig) -> ConfigurationResult<()>;
    
    /// 解密配置
    async fn decrypt(&self, config: &mut RustCloudConfig) -> ConfigurationResult<()>;
    
    /// 加密单个值
    async fn encrypt_value(&self, value: &str) -> ConfigurationResult<String>;
    
    /// 解密单个值
    async fn decrypt_value(&self, encrypted_value: &str) -> ConfigurationResult<String>;
    
    /// 检查值是否已加密
    fn is_encrypted(&self, value: &str) -> bool;
    
    /// 获取加密算法名称
    fn algorithm_name(&self) -> &str;
}

/// 配置审计抽象接口
/// 
/// 提供配置变更审计的统一接口
#[async_trait]
pub trait ConfigurationAudit: Send + Sync {
    /// 记录配置变更
    async fn log_change(&self, change: &ConfigurationChange) -> ConfigurationResult<()>;
    
    /// 查询变更历史
    async fn query_changes(
        &self,
        environment: Option<&ConfigEnvironment>,
        user: Option<&str>,
        start_time: Option<SystemTime>,
        end_time: Option<SystemTime>,
        limit: Option<usize>,
    ) -> ConfigurationResult<Vec<ConfigurationChange>>;
    
    /// 获取统计信息
    async fn get_statistics(
        &self,
        environment: Option<&ConfigEnvironment>,
        start_time: Option<SystemTime>,
        end_time: Option<SystemTime>,
    ) -> ConfigurationResult<AuditStatistics>;
    
    /// 清理过期记录
    async fn cleanup_expired(&self, before: SystemTime) -> ConfigurationResult<u64>;
}

/// 审计统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditStatistics {
    /// 总变更次数
    pub total_changes: u64,
    /// 创建次数
    pub create_count: u64,
    /// 更新次数
    pub update_count: u64,
    /// 删除次数
    pub delete_count: u64,
    /// 回滚次数
    pub rollback_count: u64,
    /// 活跃用户数
    pub active_users: u64,
    /// 活跃应用数
    pub active_applications: u64,
    /// 统计时间范围
    pub time_range: (SystemTime, SystemTime),
}

/// 配置缓存抽象接口
/// 
/// 提供配置缓存的统一接口，支持多级缓存策略
#[async_trait]
pub trait ConfigurationCache: Send + Sync {
    /// 获取缓存配置
    async fn get(&self, environment: &ConfigEnvironment) -> ConfigurationResult<Option<ConfigurationData>>;
    
    /// 设置缓存配置
    async fn put(&self, data: &ConfigurationData) -> ConfigurationResult<()>;
    
    /// 删除缓存配置
    async fn remove(&self, environment: &ConfigEnvironment) -> ConfigurationResult<()>;
    
    /// 清空所有缓存
    async fn clear(&self) -> ConfigurationResult<()>;
    
    /// 检查是否存在
    async fn contains(&self, environment: &ConfigEnvironment) -> ConfigurationResult<bool>;
    
    /// 检查是否过期
    async fn is_expired(&self, environment: &ConfigEnvironment) -> ConfigurationResult<bool>;
    
    /// 获取缓存统计
    async fn get_stats(&self) -> ConfigurationResult<CacheStatistics>;
    
    /// 刷新缓存
    async fn refresh(&self, environment: &ConfigEnvironment) -> ConfigurationResult<()>;
    
    /// 获取缓存大小
    async fn size(&self) -> ConfigurationResult<usize>;
    
    /// 列出所有缓存键
    async fn list_keys(&self) -> ConfigurationResult<Vec<ConfigEnvironment>>;
}

/// 缓存统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheStatistics {
    /// 缓存命中次数
    pub hit_count: u64,
    /// 缓存未命中次数
    pub miss_count: u64,
    /// 缓存命中率
    pub hit_rate: f64,
    /// 缓存大小
    pub size: usize,
    /// 最大容量
    pub max_capacity: usize,
    /// 过期条目数
    pub expired_count: u64,
}

/// 配置通知抽象接口
/// 
/// 提供配置变更通知的统一接口
#[async_trait]
pub trait ConfigurationNotifier: Send + Sync {
    /// 发送配置变更通知
    async fn notify(&self, event: ConfigurationEvent) -> ConfigurationResult<()>;
    
    /// 订阅配置变更
    async fn subscribe(&self, environment: &ConfigEnvironment) -> ConfigurationResult<ConfigurationEventReceiver>;
    
    /// 取消订阅
    async fn unsubscribe(&self, environment: &ConfigEnvironment) -> ConfigurationResult<()>;
    
    /// 获取订阅者数量
    async fn subscriber_count(&self, environment: &ConfigEnvironment) -> ConfigurationResult<usize>;
    
    /// 广播事件到所有订阅者
    async fn broadcast(&self, event: ConfigurationEvent) -> ConfigurationResult<()>;
}

/// 配置事件接收器
pub type ConfigurationEventReceiver = tokio::sync::mpsc::Receiver<ConfigurationEvent>;

/// 配置权限控制抽象接口
/// 
/// 提供配置权限管理的统一接口
#[async_trait]
pub trait ConfigurationAuthorization: Send + Sync {
    /// 检查读取权限
    async fn can_read(&self, user: &str, environment: &ConfigEnvironment) -> ConfigurationResult<bool>;
    
    /// 检查写入权限
    async fn can_write(&self, user: &str, environment: &ConfigEnvironment) -> ConfigurationResult<bool>;
    
    /// 检查删除权限
    async fn can_delete(&self, user: &str, environment: &ConfigEnvironment) -> ConfigurationResult<bool>;
    
    /// 获取用户可访问的应用列表
    async fn get_accessible_applications(&self, user: &str) -> ConfigurationResult<Vec<String>>;
    
    /// 获取用户权限
    async fn get_permissions(&self, user: &str, environment: &ConfigEnvironment) -> ConfigurationResult<Vec<Permission>>;
}

/// 权限类型
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Permission {
    /// 读取权限
    Read,
    /// 写入权限
    Write,
    /// 删除权限
    Delete,
    /// 管理权限
    Admin,
}